from ninja.security import HttpBearer
from jose import jwt
from django.conf import settings
from django.contrib.auth import get_user_model
from ..models import UserRole

CustomUser = get_user_model()

class RoleAuth(HttpBearer):
    """基于角色的权限验证基类"""
    def __init__(self, allowed_roles):
        super().__init__() #显示调用父类初始化
        self.allowed_roles = allowed_roles

    def authenticate(self, request, token: str):
        try:
            payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
            user = CustomUser.objects.get(id=payload["sub"])
            if user.role in self.allowed_roles:
                return user
        except (jwt.JWTError, CustomUser.DoesNotExist):
            return None

class AdminAuth(RoleAuth):
    """管理员权限验证（允许admin角色）"""
    def __init__(self):
        super().__init__(allowed_roles=[UserRole.ADMIN])

class DispatcherAuth(RoleAuth):
    """调度员权限验证（允许dispatcher角色）"""
    def __init__(self):
        super().__init__(allowed_roles=[UserRole.DISPATCHER])